package com.liuqi.voicenotes

import android.Manifest
import android.Manifest.permission.POST_NOTIFICATIONS
import android.app.AlarmManager
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.speech.RecognizerIntent
import android.speech.tts.TextToSpeech
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.AssistChip
import androidx.compose.material3.Card
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TimePicker
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.lifecycle.lifecycleScope
import com.liuqi.voicenotes.data.Priority
import com.liuqi.voicenotes.data.Task
import com.liuqi.voicenotes.data.TaskRepository
import com.liuqi.voicenotes.domain.Parser
import com.liuqi.voicenotes.reminder.SpeechUtils
import com.liuqi.voicenotes.ui.TasksViewModel
import com.liuqi.voicenotes.ui.VoiceNotesTheme
import com.liuqi.voicenotes.ui.VoiceChatOverlay
import kotlinx.coroutines.launch
import java.util.Locale
import androidx.core.content.edit

// 定义枚举类
enum class StatusFilter { All, Active, Completed }
enum class DateFilter { All, Today, ThisWeek, Overdue }

class MainActivity : ComponentActivity() {
    private lateinit var sharedPreferences: SharedPreferences
    private lateinit var tts: TextToSpeech

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        tts = TextToSpeech(this) { status ->
            if (TextToSpeech.SUCCESS == status) {
                tts.setLanguage(Locale.CHINESE)
            }
        }
        sharedPreferences = getSharedPreferences("voicenotes_prefs", Context.MODE_PRIVATE)
        ensureNotificationChannel()
        maybeCreateStartupTestTask()
        setContent { App(tts, this) }
    }
    private fun ensureNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "voicenotes.reminders",
                "待办提醒",
                NotificationManager.IMPORTANCE_HIGH
            )
            (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
                .createNotificationChannel(channel)

            val speechChannel = NotificationChannel(
                "voicenotes.speech",
                "语音提醒",
                NotificationManager.IMPORTANCE_LOW
            )
            (getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager)
                .createNotificationChannel(speechChannel)
        }
    }

    // 启动时自动创建一个测试任务：在"提前提醒"后约2分钟触发语音预提醒
    private fun maybeCreateStartupTestTask() {
        // 每次启动都创建一个测试任务
        val leadMinutes = com.liuqi.voicenotes.reminder.ReminderScheduler.getLeadMinutes(this)
        // 预提醒在当前时间约2分钟后触发：due = now + lead + 2分钟
        val now = System.currentTimeMillis()
        val dueAt = now + leadMinutes * 60_000L + 2 * 60_000L

        val repo = TaskRepository(this)
        lifecycleScope.launch {
            try {
                val title = "测试语音提醒"
                val task = Task(id = 0, title = title, dueAtMillis = dueAt, priority = Priority.MEDIUM, completed = false)
                val id = repo.add(task)
                com.liuqi.voicenotes.reminder.ReminderScheduler.scheduleForTask(this@MainActivity, id, title, dueAt)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun App(tts: TextToSpeech, context: Context) {
    VoiceNotesTheme {
        val context = LocalContext.current
        val viewModel = remember { TasksViewModel(TaskRepository(context), context) }
        val tasks by viewModel.tasks.collectAsState(initial = emptyList())
        var filter by remember { mutableStateOf<Priority?>(null) }
        var statusFilter by remember { mutableStateOf(StatusFilter.All) }
        var dateFilter by remember { mutableStateOf(DateFilter.All) }
        var editing by remember { mutableStateOf<Task?>(null) }
        var showSettings by remember { mutableStateOf(false) }
        var showVoiceOverlay by remember { mutableStateOf(false) }
        var isVoiceProcessing by remember { mutableStateOf(false) }
        var overlayStartAt by remember { mutableStateOf(0L) }

        val recordPermissionLauncher = rememberLauncherForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { isGranted ->
            if (isGranted) {
                // 检查并请求SCHEDULE_EXACT_ALARM权限（如果需要）
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                    val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
                    if (!alarmManager.canScheduleExactAlarms()) {
                        // 在实际应用中，你可能需要引导用户到设置页面开启权限
                        // 这里为了简化，我们只记录日志
                        println("需要精确闹钟权限来设置提醒")
                    }
                }
            }
        }

        val notiPermissionLauncher = rememberLauncherForActivityResult(
            ActivityResultContracts.RequestPermission()
        ) { }

        val speechLauncher = rememberLauncherForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            val data = result.data
            val texts = data?.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS)
            val first = texts?.firstOrNull()
            Log.d("MainActivity", "Speech first='${first}'")
            if (!first.isNullOrBlank()) {
                val activity = (context as? MainActivity)
                activity?.lifecycleScope?.launch {
                    val parsed = Parser.parseSpeechToTask(context, first, 0)
                    val speakText = parsed?.title ?: first
                    Log.d("MainActivity", "Parsed: title='${parsed?.title}' due=${parsed?.dueAtMillis} priority=${parsed?.priority}")
                    tts.speak(speakText, TextToSpeech.QUEUE_FLUSH, null)
                    SpeechUtils.speakNow(context, speakText)
                    if (parsed != null) {
                        viewModel.addParsedTask(parsed)
                    } else {
                        viewModel.addFromSpeech(first)
                    }
                    Log.d("MainActivity", "Added task from speech launcher")
                }
            }
        }

        Scaffold(
            topBar = {
                TopAppBar(
                    title = { Text("语音记事本") },
                    actions = {
                        TextButton(onClick = { showSettings = true }) { Text("设置") }
                    }
                )
            },
            floatingActionButton = {
                FloatingActionButton(onClick = {
                    recordPermissionLauncher.launch(Manifest.permission.RECORD_AUDIO)
                    if (Build.VERSION.SDK_INT >= 33) {
                        notiPermissionLauncher.launch(POST_NOTIFICATIONS)
                    }
                    // 改为弹出按住说话的覆盖层
                    showVoiceOverlay = true
                    overlayStartAt = System.currentTimeMillis()
                }) {
                    Text("语音")
                }
            }
        ) { padding ->
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(padding)
                    .padding(16.dp)
            ) {
                Text("待办列表", style = MaterialTheme.typography.titleMedium)
                Spacer(Modifier.height(8.dp))
                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    FilterChip(selected = filter == null, onClick = { filter = null }, label = { Text("全部") })
                    FilterChip(selected = filter == Priority.HIGH, onClick = { filter = Priority.HIGH }, label = { Text("高") })
                    FilterChip(selected = filter == Priority.MEDIUM, onClick = { filter = Priority.MEDIUM }, label = { Text("中") })
                    FilterChip(selected = filter == Priority.LOW, onClick = { filter = Priority.LOW }, label = { Text("低") })
                }
                Spacer(Modifier.height(8.dp))
                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    FilterChip(selected = statusFilter == StatusFilter.All, onClick = { statusFilter = StatusFilter.All }, label = { Text("全部状态") })
                    FilterChip(selected = statusFilter == StatusFilter.Active, onClick = { statusFilter = StatusFilter.Active }, label = { Text("未完成") })
                    FilterChip(selected = statusFilter == StatusFilter.Completed, onClick = { statusFilter = StatusFilter.Completed }, label = { Text("已完成") })
                }
                Spacer(Modifier.height(8.dp))
                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    FilterChip(selected = dateFilter == DateFilter.All, onClick = { dateFilter = DateFilter.All }, label = { Text("全部日期") })
                    FilterChip(selected = dateFilter == DateFilter.Today, onClick = { dateFilter = DateFilter.Today }, label = { Text("今天") })
                    FilterChip(selected = dateFilter == DateFilter.ThisWeek, onClick = { dateFilter = DateFilter.ThisWeek }, label = { Text("本周") })
                    FilterChip(selected = dateFilter == DateFilter.Overdue, onClick = { dateFilter = DateFilter.Overdue }, label = { Text("已过期") })
                }
                Spacer(Modifier.height(8.dp))
                val nowMillis = System.currentTimeMillis()
                val filteredByPriority = tasks.filter { filter == null || it.priority == filter }
                val filteredByDate = when (dateFilter) {
                    DateFilter.All -> filteredByPriority
                    DateFilter.Today -> filteredByPriority.filter { it.dueAtMillis?.let { m -> isToday(m) } == true }
                    DateFilter.ThisWeek -> filteredByPriority.filter { it.dueAtMillis?.let { m -> isThisWeek(m) } == true }
                    DateFilter.Overdue -> filteredByPriority.filter { it.dueAtMillis?.let { m -> m < nowMillis } == true && !it.completed }
                }
                val filtered = filteredByDate.filter {
                    when (statusFilter) {
                        StatusFilter.All -> true
                        StatusFilter.Active -> !it.completed
                        StatusFilter.Completed -> it.completed
                    }
                }
                val active = filtered.filter { !it.completed }
                val completed = filtered.filter { it.completed }
                LazyColumn(modifier = Modifier.fillMaxSize()) {
                    if (statusFilter != StatusFilter.Completed) {
                        item { Text("未完成", style = MaterialTheme.typography.titleSmall) }
                        items(active, key = { it.id }) { task ->
                            TaskItem(
                                task = task,
                                onEdit = { editing = task },
                                onDelete = { viewModel.delete(task) },
                                onToggleComplete = { viewModel.toggleCompleted(task) }
                            )
                        }
                    }
                    if (statusFilter != StatusFilter.Active) {
                        item { Spacer(Modifier.height(12.dp)) }
                        item { Text("已完成", style = MaterialTheme.typography.titleSmall) }
                        items(completed, key = { it.id }) { task ->
                            TaskItem(
                                task = task,
                                onEdit = { editing = task },
                                onDelete = { viewModel.delete(task) },
                                onToggleComplete = { viewModel.toggleCompleted(task) }
                            )
                        }
                    }
                }
                editing?.let { t ->
                    EditTaskDialog(
                        task = t,
                        onDismiss = { editing = null },
                        onSave = { updated ->
                            viewModel.update(updated)
                            editing = null
                        }
                    )
                }
            }

            if (showSettings) {
                AlertDialog(
                    onDismissRequest = { showSettings = false },
                    confirmButton = {
                        TextButton(onClick = { showSettings = false }) { Text("关闭") }
                    },
                    title = { Text("设置") },
                    text = {
                        Column {
                            var lead by remember { mutableStateOf(com.liuqi.voicenotes.reminder.ReminderScheduler.getLeadMinutes(context)) }
                            Text("到期前提前提醒分钟数：$lead 分")
                            Spacer(Modifier.height(8.dp))
                            Slider(value = lead.toFloat(), onValueChange = { lead = it.toInt() }, valueRange = 0f..60f, steps = 59)
                            Spacer(Modifier.height(8.dp))
                            TextButton(onClick = {
                                com.liuqi.voicenotes.reminder.ReminderScheduler.setLeadMinutes(context, lead)
                            }) { Text("保存提前提醒") }
                            Spacer(Modifier.height(16.dp))
                            var apiKey by remember { mutableStateOf(context.getSharedPreferences("voicenotes_prefs", Context.MODE_PRIVATE).getString("deepseek_api_key", "sk-d61c709c7afc40eda43afc076afd3550") ?: "sk-d61c709c7afc40eda43afc076afd3550") }
                            var apiBase by remember { mutableStateOf(context.getSharedPreferences("voicenotes_prefs", Context.MODE_PRIVATE).getString("deepseek_api_base", "https://api.deepseek.com") ?: "https://api.deepseek.com") }
                            OutlinedTextField(value = apiKey, onValueChange = { apiKey = it }, label = { Text("DeepSeek API Key") }, singleLine = true)
                            Spacer(Modifier.height(8.dp))
                            OutlinedTextField(value = apiBase, onValueChange = { apiBase = it }, label = { Text("DeepSeek API Base") }, singleLine = true)
                            Spacer(Modifier.height(8.dp))
                            TextButton(onClick = {
                                context.getSharedPreferences("voicenotes_prefs", Context.MODE_PRIVATE)
                                    .edit {
                                        putString("deepseek_api_key", apiKey)
                                            .putString("deepseek_api_base", apiBase)
                                    }
                            }) { Text("保存大模型配置") }
                        }
                    }
                )
            }
        }
        
        // 在最顶层条件渲染语音覆盖层
        if (showVoiceOverlay) {
            VoiceChatOverlay(
                processing = isVoiceProcessing,
                onFinalText = { text ->
                    val activity = (context as? MainActivity)
                    isVoiceProcessing = true
                    activity?.lifecycleScope?.launch {
                        try {
                            Log.d("MainActivity", "Voice final text='${text}', start LLM parse")
                            val parsed = Parser.parseSpeechToTask(context, text, 0)
                            val speakText = parsed?.title ?: text
                            Log.d("MainActivity", "Parsed: title='${parsed?.title}' due=${parsed?.dueAtMillis} priority=${parsed?.priority}")
                            SpeechUtils.speakNow(context, speakText)
                            if (parsed != null) {
                                viewModel.addParsedTask(parsed)
                            } else {
                                viewModel.addFromSpeech(text)
                            }
                            Log.d("MainActivity", "Added task from voice")
                        } finally {
                            isVoiceProcessing = false
                            // 最小停留时长，避免界面瞬时消失影响调试体验
                            val stay = System.currentTimeMillis() - overlayStartAt
                            if (stay < 900) {
                                kotlinx.coroutines.delay(900 - stay)
                            }
                            showVoiceOverlay = false
                            Log.d("MainActivity", "Close overlay after processing, stay=${System.currentTimeMillis() - overlayStartAt}ms")
                        }
                    }
                },
                onDismiss = {
                    if (!isVoiceProcessing) {
                        showVoiceOverlay = false
                    } else {
                        Log.d("MainActivity", "Dismiss ignored: processing in progress")
                    }
                }
            )
        }
    }
}

@Composable
private fun TaskItem(
    task: Task,
    onEdit: () -> Unit,
    onDelete: () -> Unit,
    onToggleComplete: () -> Unit
) {
    Card(modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) {
        Row(
            modifier = Modifier.padding(12.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(task.title, style = MaterialTheme.typography.bodyLarge)
                val due = task.dueAtMillis?.let { formatMillisPretty(it) }
                Text("时间：${due ?: "未设置"}", style = MaterialTheme.typography.bodySmall)
                val color = when (task.priority) {
                    Priority.HIGH -> MaterialTheme.colorScheme.error
                    Priority.MEDIUM -> MaterialTheme.colorScheme.primary
                    Priority.LOW -> MaterialTheme.colorScheme.outline
                }
                Row(verticalAlignment = Alignment.CenterVertically) {
                    androidx.compose.foundation.layout.Box(
                        modifier = Modifier.size(8.dp).then(
                            Modifier.background(color, shape = androidx.compose.foundation.shape.CircleShape)
                        )
                    )
                    Spacer(Modifier.width(6.dp))
                    Text("优先级：${task.priority}", style = MaterialTheme.typography.bodySmall, color = color)
                }
            }
            Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                TextButton(onClick = onEdit) { Text("编辑") }
                TextButton(onClick = onToggleComplete) { Text(if (task.completed) "未完成" else "完成") }
                TextButton(onClick = onDelete) { Text("删除") }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun EditTaskDialog(
    task: Task,
    onDismiss: () -> Unit,
    onSave: (Task) -> Unit
) {
    var title by remember { mutableStateOf(task.title) }
    var priority by remember { mutableStateOf(task.priority) }
    var dueMillis by remember { mutableStateOf(task.dueAtMillis) }
    var showDatePicker by remember { mutableStateOf(false) }
    var showTimePicker by remember { mutableStateOf(false) }
    val initialDateMillis = task.dueAtMillis
    val dateState = rememberDatePickerState(initialSelectedDateMillis = initialDateMillis)
    val initHour = task.dueAtMillis?.let { java.time.Instant.ofEpochMilli(it).atZone(java.time.ZoneId.systemDefault()).hour } ?: 9
    val initMinute = task.dueAtMillis?.let { java.time.Instant.ofEpochMilli(it).atZone(java.time.ZoneId.systemDefault()).minute } ?: 0
    val timeState = rememberTimePickerState(initialHour = initHour, initialMinute = initMinute, is24Hour = true)

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("编辑任务") },
        text = {
            Column { 
                OutlinedTextField(value = title, onValueChange = { title = it }, label = { Text("标题") })
                Spacer(Modifier.height(8.dp))
                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    AssistChip(onClick = { priority = Priority.HIGH }, label = { Text("高") })
                    AssistChip(onClick = { priority = Priority.MEDIUM }, label = { Text("中") })
                    AssistChip(onClick = { priority = Priority.LOW }, label = { Text("低") })
                }
                Spacer(Modifier.height(8.dp))
                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    TextButton(onClick = { showDatePicker = true }) { Text("选择日期") }
                    TextButton(onClick = { showTimePicker = true }) { Text("选择时间") }
                    TextButton(onClick = { dueMillis = null }) { Text("清除时间") }
                }
                val dueStr = dueMillis?.let { formatMillisPretty(it) } ?: "未设置"
                Text("当前提醒时间：$dueStr", style = MaterialTheme.typography.bodySmall)
            }
        },
        confirmButton = {
            TextButton(onClick = {
                onSave(task.copy(title = title, priority = priority, dueAtMillis = dueMillis))
            }) { Text("保存") }
        },
        dismissButton = { TextButton(onClick = onDismiss) { Text("取消") } }
    )

    if (showDatePicker) {
        DatePickerDialog(onDismissRequest = { showDatePicker = false }, confirmButton = {
            TextButton(onClick = {
                val selected = dateState.selectedDateMillis
                if (selected != null) {
                    val date = java.time.Instant.ofEpochMilli(selected).atZone(java.time.ZoneId.systemDefault()).toLocalDate()
                    val current = dueMillis?.let { java.time.Instant.ofEpochMilli(it).atZone(java.time.ZoneId.systemDefault()).toLocalTime() } ?: java.time.LocalTime.of(timeState.hour, timeState.minute)
                    val ldt = java.time.LocalDateTime.of(date, current)
                    dueMillis = ldt.atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli()
                }
                showDatePicker = false
            }) { Text("确定") }
        }) {
            DatePicker(state = dateState)
        }
    }

    if (showTimePicker) {
        AlertDialog(onDismissRequest = { showTimePicker = false }, confirmButton = {
            TextButton(onClick = {
                val date = dueMillis?.let { java.time.Instant.ofEpochMilli(it).atZone(java.time.ZoneId.systemDefault()).toLocalDate() }
                    ?: java.time.LocalDate.now()
                val ldt = java.time.LocalDateTime.of(date, java.time.LocalTime.of(timeState.hour, timeState.minute))
                dueMillis = ldt.atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli()
                showTimePicker = false
            }) { Text("确定") }
        }, dismissButton = { TextButton(onClick = { showTimePicker = false }) { Text("取消") } }, text = {
            TimePicker(state = timeState)
        }, title = { Text("选择时间") })
    }
}

